<template>
  <Modal
    v-model="form.visible"
    :width="1000"
    :mask-closable="false"
    :loading="loading"
    :title="form.data.id ? '修改活动组别' : '新增活动组别'"
    ok-text="提交"
    @on-ok="ok">
    <Row class="mt30">
      <Col span="16" offset="4">
        <Form ref="form" :model="form.data" :rules="ruleValidate" :label-width="150">
          <FormItem prop="group_type" label="组别分类">
            <Select v-model="form.data.group_type" style="width: 100%" placeholder="请选择组别分类">
              <Option
                v-for="item in groupTypeCodeList"
                :key="item.code"
                :value="'' + item.code">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <Row>
            <Col span="12">
              <FormItem prop="group_name" label="组别名称">
                <Input v-model="form.data.group_name" placeholder="请输入"></Input>
              </FormItem>
              <FormItem prop="low_age" label="年龄要求">
                <InputNumber :min="0" :max="99" v-model.number="form.data.low_age" placeholder="请输入"></InputNumber>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem prop="total_km" label="公里数（KM）">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.total_km" placeholder="请输入"></InputNumber>
              </FormItem>
              <FormItem prop="high_age" label="至" :label-width="150">
                <InputNumber :min="0" :max="99" v-model.number="form.data.high_age" placeholder="请输入"></InputNumber>
              </FormItem>
            </Col>
          </Row>

          <FormItem prop="age_memo" label="年龄要求说明">
            <Input type="textarea" v-model="form.data.age_memo" placeholder="请输入" :rows="4"></Input>
          </FormItem>

          <Row>
            <Col span="12">
              <FormItem prop="sign_up_fee" label="报名费">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.sign_up_fee" placeholder="请输入"></InputNumber>
              </FormItem>
            </Col>
            <Col span="11" offset="1">
              <FormItem prop="insurance_fee" label="保险费">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.insurance_fee" placeholder="请输入"></InputNumber>
              </FormItem>
            </Col>
          </Row>

          <FormItem prop="fee_memo" label="报名费说明">
            <Input type="textarea" v-model="form.data.fee_memo" placeholder="请输入" :rows="4"></Input>
          </FormItem>

          <Row>
            <Col span="12">
              <FormItem prop="start_time" label="发车时间">
                <DatePicker type="datetime" :options="options.start_time" style="width:100%" placeholder="选择日期" v-model="form.data.start_time"></DatePicker>
              </FormItem>
              <FormItem prop="limit_time" label="限时（小时）">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.limit_time" placeholder="请输入"></InputNumber>
              </FormItem>
              <FormItem prop="sign_up_count" label="可报名人数">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.sign_up_count" placeholder="请输入"></InputNumber>
              </FormItem>
            </Col>
            <Col span="11" offset="1">
              <FormItem prop="close_time" label="关门时间">
                <DatePicker type="datetime" :options="options.close_time" style="width:100%" placeholder="选择日期" v-model="form.data.close_time"></DatePicker>
              </FormItem>
              <FormItem prop="acc_points" label="积分">
                <InputNumber :min="0" :max="9999" v-model.number="form.data.acc_points" placeholder="请输入"></InputNumber>
              </FormItem>
              <FormItem prop="if_show" label="是否外网显示">
                <Select v-model="form.data.if_show" style="width:100%">
                  <Option :value="0">显示</Option>
                  <Option :value="1">不显示</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <FormItem prop="group_image" label="组别图片">
            <upload-img v-if="form.visible" @on-change="onUploadImg" :defaultImageList="defaultImageList"></upload-img>
          </FormItem>
          <FormItem prop="remark" label="组别说明">
            <Input type="textarea" v-model="form.data.remark" placeholder="请输入" :rows="4"></Input>
          </FormItem>
        </Form>
      </Col>
    </Row>
  </Modal>
</template>

<script>
  import Vue from 'vue'
  import { mapGetters } from 'vuex'
  import uploadImg from '@/components/upload-img'

  import activityApi from '@/api/activity'

  export default {
    name: 'update-modal',
    props: [
      'form'
    ],
    components: {
      uploadImg
    },
    data () {
      const validateAge = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入结束年龄'))
        } else if (value < this.form.data.low_age) {
          callback(new Error('结束年龄应大于开始年龄!'))
        } else {
          callback()
        }
      }
      return {
        loading: true,
        ruleValidate: {
          group_type: [
            { required: true, message: '请选择组别分类', trigger: 'change' }
          ],
          group_name: [
            { required: true, message: '请输入组别名称', trigger: 'change' },
            { min: 1, max: 50, message: '组别名称字符长度应小于50', trigger: 'change' }
          ],
          low_age: [
            { required: true, type: 'number', message: '请输入开始年龄', trigger: 'change' }
          ],
          high_age: [
            { required: true, type: 'number', validator: validateAge, trigger: 'change' }
          ],
          total_km: [
            { required: true, type: 'number', message: '请输入公里数', trigger: 'change' }
          ],
          age_memo: [
            { max: 100, message: '年龄说明字符长度应小于100', trigger: 'change' }
          ],
          sign_up_fee: [
            { required: true, type: 'number', message: '请输入报名费', trigger: 'change' }
          ],
          insurance_fee: [
            { required: true, type: 'number', message: '请输入保险费', trigger: 'change' }
          ],
          fee_memo: [
            { max: 100, message: '报名费说明字符长度应小于100', trigger: 'change' }
          ],
          start_time: [
            { required: true, type: 'date', message: '请选择发车时间', trigger: 'change' }
          ],
          close_time: [
            { required: true, type: 'date', message: '请选择关门时间', trigger: 'change' }
          ],
          limit_time: [
            { max: 9999, type: 'number', message: '限时(小时)字符长度应小于5', trigger: 'change' }
          ],
          sign_up_count: [
            { required: true, type: 'number', message: '请输入可报名人数', trigger: 'change' }
          ],
          acc_points: [
            { max: 9999, type: 'number', message: '积分字符长度应小于5', trigger: 'change' }
          ],
          if_show: [
            { required: true, type: 'number', message: '请选择是否外网显示', trigger: 'change' }
          ],
          group_image: [
            { required: true, message: '请上传组别图片', trigger: 'change' }
          ],
          remark: [
            { max: 100, message: '组别说明字符长度应小于100', trigger: 'change' }
          ]
        },
        options: {
          start_time: {},
          close_time: {}
        }
      }
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo',
        groupTypeCodeList: 'groupTypeCodeList'
      })
    },
    watch: {
      'form.visible': 'onClose',
      'form.data.start_time': function (val, oldVal) {
        this.options.close_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.start_time) {
            isDisabled = date && date.valueOf() < this.form.data.start_time.getTime()
          }
          return isDisabled
        }
      },
      'form.data.close_time': function (val, oldVal) {
        this.options.start_time.disabledDate = (date) => {
          let isDisabled = false
          if (this.form.data.close_time) {
            isDisabled = date && date.valueOf() > this.form.data.close_time.getTime()
          }
          return isDisabled
        }
      }
    },
    methods: {
      ok () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitForm()
          } else {
            this.$Message.error('表单验证失败，请检查输入内容!')
            this.form.visible = true
            this.loading = false
            setTimeout(() => {
              this.loading = true
            }, 100)
          }
        })
      },
      onClose (isVisible) {
        if (!isVisible) {
          this.$refs.form.resetFields()
        } else {
          this.defaultImageList = Vue.filter('splitImg')(this.form.data.group_image || '')
        }
      },
      onUploadImg (imgList) {
        this.form.data.group_image = imgList.filter((item) => {
          return item.name.length > 0
        }).map((item) => {
          if (item.response && item.response.responseData) {
            return item.response.responseData
          } else {
            return item.name
          }
        }).join(',')
        this.$refs.form.validateField('group_image')
      },

      async submitForm () {
        let activityId = this.$route.params.activityId
        this.form.data.pk_act_base_info = activityId
        if (this.form.data.id) {
          const { body } = await activityApi.group.update(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('修改成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
              this.loading = false
            }, 500)
          }
        } else {
          const { body } = await activityApi.group.create(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('创建成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
              this.loading = false
            }, 500)
          }
        }
      }
    },
    mounted () {
      this.$store.dispatch('getCode', 'group_type')
    }
  }
</script>
